package cn.tianya.irock.security;


import java.security.Principal;
import java.util.List;

import cn.tianya.irock.bll.Users;
import cn.tianya.irock.enums.LoginUserStatus;

import flex.messaging.FlexContext;
import flex.messaging.security.AppServerLoginCommand;


public class FlexLoginCommand extends AppServerLoginCommand {
	//private static final int NO_VALVE = 20000;
	
	public Principal doAuthentication(String username, Object credentials) throws SecurityException {
		FlexUser ruser = null;		
		System.out.print("auth\n");
		if (Users.validUser(FlexContext.getHttpRequest().getCookies()) == LoginUserStatus.Success) {
			ruser = new FlexUser(username, "");
		} else {
			System.out.print("doAuthentication fails\n");
		}

		System.out.print("doAuthentication succes\n");
        return ruser;
	}

	public boolean doAuthorization(Principal principal, List roles) throws SecurityException
	{
	    boolean authorized = false;
	/*
	    HttpServletRequest request = FlexContext.getHttpRequest();
	    HttpServletResponse response = FlexContext.getHttpResponse(); // Response is null for NIO endpoints.
	    
	    if (response != null && request != null &&
	        principal != null && principal.equals(request.getUserPrincipal()))
	    {
	        authorized = doAuthorization(principal, roles, request);
	    }
	    else
	    {
	        TomcatLogin login = TomcatLoginHolder.getLogin();
	        if (login == null)
	        {
	            SecurityException se =
	                new SecurityException(new PropertyStringResourceLoader(PropertyStringResourceLoader.VENDORS_BUNDLE));
	            se.setMessage(NO_VALVE);
	            throw se;
	        }
	        authorized = login.authorize(principal, roles);
	    }
	*/
	    System.out.print("doAuthorization false!\n");
	    return authorized;
	}
	
	/** {@inheritDoc} */
	public boolean logout(Principal principal) throws SecurityException
	{
	    /*HttpServletRequest request = FlexContext.getHttpRequest();
	    HttpServletResponse response = FlexContext.getHttpResponse(); // Response is null for NIO endpoints.
	    if (response != null && request != null)
	    {
	        TomcatLogin login = TomcatLoginHolder.getLogin();
	        if (login != null)
	        {
	            return login.logout(request);
	        }
	        else
	        {
	            //TODO should we do this?
	            //request.getSession(false).invalidate();
	        }
	    }*/
		System.out.print("logout!\n");
	    return true;
	}
}
